package com.eslserver.action.esl;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.action.helper.PushESLHTTPMultipartPost;
import com.eslserver.core.ESLServerPageDispatcher;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.to.Coordinator;
import com.eslserver.to.ESL;
import com.eslserver.to.Image;

@SuppressWarnings("serial")
public class PushESLDisplayAction extends HttpServlet implements
		ESLServerPageDispatcher {
	public static final Logger LOG = LoggerFactory
			.getLogger(PushESLDisplayAction.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();

			String[] selectedCheckboxes = req
					.getParameterValues(PARAM_ALL_SELECTED_CB);

			StringBuffer pushMessage = new StringBuffer();
			if (selectedCheckboxes != null) {
				for (String eslID : selectedCheckboxes) {
					ESL esl = eslDAO.loadESL(Integer.valueOf(eslID));
					Image eslImage = esl.getImages().iterator().next();
					Coordinator coordinator = esl.getCoordinator();

					LOG.info("Starting push job for " + esl.getName());

					PushESLHTTPMultipartPost pushESLHTTPMultipartPost = new PushESLHTTPMultipartPost(
							esl, coordinator, eslImage);
					pushMessage.append(pushESLHTTPMultipartPost.sendHTTPPost());

					LOG.info("Ended push job for " + esl.getName());
				}
			}

			req.setAttribute(ATTRIBUTE_PUSH_MESSAGE, pushMessage);
			RequestDispatcher dispatcher = req
					.getRequestDispatcher(MAIN_DASHBOARD);
			dispatcher.forward(req, resp);
		} catch (DAOException e) {
			LOG.error("error laoding ESL", e);
		}
	}
}
